package br.com.gfkauer.model.facade;

import java.io.Serializable;
import java.util.List;

import br.com.gfkauer.model.dao.ClientDAO;
import br.com.gfkauer.model.dao.EquipmentDAO;
import br.com.gfkauer.model.entity.Client;
import br.com.gfkauer.model.entity.Equipment;

public class ClientFacade implements Serializable{

	private static final long serialVersionUID = 1L;

	private ClientDAO clientDAO = new ClientDAO();
	private EquipmentDAO equipDAO = new EquipmentDAO();
	
	public void createClient(Client client){
		clientDAO.beginTransactio();
		clientDAO.save(client);
		clientDAO.commitAndCloseTransaction();
	}
	
	public void updateClient(Client client){
		clientDAO.beginTransactio();
		Client persistedClient = clientDAO.find(client.getId());
		persistedClient.setBairro(client.getBairro());
		persistedClient.setCep(client.getCep());
		persistedClient.setCidade(client.getCidade());
		persistedClient.setCompl(client.getCompl());
		persistedClient.setDoc(client.getDoc());
		persistedClient.setEmail(client.getEmail());
		persistedClient.setFone(client.getFone());
		persistedClient.setLogradouro(client.getLogradouro());
		persistedClient.setNome(client.getNome());
		persistedClient.setTipoPessoa(client.getTipoPessoa());
		clientDAO.update(persistedClient);
		clientDAO.commitAndCloseTransaction();
	}
	
	public void deleteClient(Client client){
		clientDAO.beginTransactio();
		Client persistedClient = clientDAO.findRefenceOnly(client.getId());
		clientDAO.delete(persistedClient);
		clientDAO.commitAndCloseTransaction();
	}
	
	public Client findClient(int clientId){
		clientDAO.beginTransactio();
		Client client = clientDAO.find(clientId);
		clientDAO.closeTransaction();
		return client;
	}
	
	public List<Client> listAll(){
		clientDAO.beginTransactio();
		List<Client> result = clientDAO.findAll();
		clientDAO.closeTransaction();
		return result;
	}
	
	public Client findClientWithAllEquips(int clientId){
		clientDAO.beginTransactio();
		Client client = clientDAO.findClientByDocWithEquips(clientId);
		clientDAO.closeTransaction();
		return client;
	}
	
	public void addEquipToClient(int equipId, int clientId){
		clientDAO.beginTransactio();
		equipDAO.joinTransaction();
		Equipment equipment = equipDAO.find(equipId);
		Client client = clientDAO.find(clientId);
		client.getEquipments().add(equipment);
		equipment.getClients().add(client);
		clientDAO.commitAndCloseTransaction();
	}
	
	public void removeEquipFromClient(int equipId, int clientId){
		clientDAO.beginTransactio();
		equipDAO.joinTransaction();
		Equipment equipment = equipDAO.find(equipId);
		Client client = clientDAO.find(clientId);
		client.getEquipments().remove(equipment);
		equipment.getClients().remove(client);
	}
	
}
